package cn.znk.kedis.master_slave_model.autoconfigure;

import cn.znk.kedis.master_slave_model.properties.RedisSlaveProperties;
import cn.znk.kedis.master_slave_model.utils.JacksonObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;


/**
 * IntelliJ IDEA
 * project: kedis-spring-boot-starter
 *
 * @author shimi
 * @since 2021/11/21
 * @version 1.0.0
 */
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties({RedisSlaveProperties.class})
public class RedisSlaveAutoConfiguration {

    @Autowired
    private RedisSlaveProperties slaveProperties;

    @Resource
    private JedisPoolConfig jedisPoolConfig;

    @Bean("slaveRedisFactory")
    public JedisConnectionFactory masterJedisConnectionFactory() {
        JedisConnectionFactory slaveFactory = new JedisConnectionFactory();
        slaveFactory.setPort(Integer.parseInt(slaveProperties.getPort()));
        slaveFactory.setHostName(slaveProperties.getHost());
        slaveFactory.setPoolConfig(jedisPoolConfig);
        slaveFactory.setTimeout(0);
        slaveFactory.setPassword(slaveProperties.getPassword());
        return slaveFactory;
    }

    @Bean
    public RedisTemplate slaveRedisTemplate(@Autowired @Qualifier("slaveRedisFactory") JedisConnectionFactory factory) {
        RedisTemplate slaveRedisTemplate = new RedisTemplate();
        slaveRedisTemplate.setConnectionFactory(factory);
        JacksonObjectUtil.setCNJacksonObject(slaveRedisTemplate);
        return slaveRedisTemplate;
    }

}
